package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuEntity;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSkuService;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuEntityRepository;
import cn.tedu.mall.search.repository.SpuForElasticRepository;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.elasticsearch.client.license.LicensesStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {

    @DubboReference
    private IForFrontSpuService dubboSpuService;
    @Autowired
    private SpuEntityRepository spuRepository;

    @Override
    public JsonPage<SpuEntity> search(String keyword, Integer page, Integer pageSize) {

        Page<SpuEntity> spus = spuRepository.
                querySearchByText(keyword, PageRequest.of(page - 1, pageSize));
        JsonPage<SpuEntity> jsonPage = new JsonPage<>();
        jsonPage.setPage(page);
        jsonPage.setPageSize(pageSize);
        jsonPage.setTotalPage(spus.getTotalPages());
        jsonPage.setTotal(spus.getTotalElements());
        jsonPage.setList(spus.toList());

        return jsonPage;
    }

    @Override
    public void loadSpuByPage() {
        int i=1;
        int page;
        do{
            //每次查一页。
            JsonPage<Spu> spus = dubboSpuService.getSpuByPage(i, 2);
            //全部页数
            page = spus.getTotalPage();

            //但泛型是Spu，且类型不是集合类？
            List<SpuEntity> esSpus = new ArrayList<>();
            for(Spu spu : spus.getList()){
                SpuEntity esSpu = new SpuEntity();
                BeanUtils.copyProperties(spu, esSpu);
                esSpus.add(esSpu);
            }
            spuRepository.saveAll(esSpus);
            log.info("{}页数据已加载到ES",i);
            i++;
        }while (i<=page);
    }
}
